package com.yu.mall.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yu.mall.dto.BaseDTO;
import com.yu.mall.dto.PageDTO;
import com.yu.mall.dto.address.AddressDTO;
import com.yu.mall.dto.user.UserDTO;
import com.yu.mall.entity.AdminUser;
import com.yu.mall.entity.White;
import com.yu.mall.service.AdminUserService;
import com.yu.mall.service.UserService;
import com.yu.mall.util.PasswordUtil;
import com.yu.mall.util.RedisUtil;
import com.yu.mall.util.ResultUtils;
import com.yu.mall.vo.PageResultVO;
import com.yu.mall.vo.ResultVO;
import com.yu.mall.vo.address.AddressVO;
import com.yu.mall.vo.user.UserVO;
import io.swagger.annotations.*;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Random;

@RestController
@RequestMapping("admin")
@Api(tags = "后台用户管理",value = "后台用户管理")
public class AdminUserController {

    @Autowired
    AdminUserService adminUserService;

    @Autowired
    RedisUtil redisUtil;

    @PostMapping("add")
    @ApiOperation(value = "添加用户")
    public ResultVO add(AdminUser adminUser){
        AdminUser example = new AdminUser();
        example.setUserName(adminUser.getUserName());
        List<AdminUser> list = adminUserService.select(example);
        if(!CollectionUtils.isEmpty(list)){
            return ResultUtils.error("用户名已存在");
        }
        adminUser.setId(null);
        adminUser.setCreateTime(new Date());
        adminUser.setUpdateTime(new Date());
        adminUserService.insertSelective(adminUser);
        return ResultUtils.success();
    }

    @PostMapping("update")
    @ApiOperation(value = "修改用户")
    public ResultVO update(AdminUser adminUser){
        AdminUser adminUser1 = adminUserService.selectByPrimaryKey(adminUser.getId());
        if(!adminUser1.getUserName().equals(adminUser.getUserName())){
            AdminUser example = new AdminUser();
            example.setUserName(adminUser.getUserName());
            List<AdminUser> list = adminUserService.select(example);
            if(!CollectionUtils.isEmpty(list)){
                return ResultUtils.error("用户名已存在");
            }
        }

        adminUser.setUpdateTime(new Date());
        int i = adminUserService.updateByPrimaryKeySelective(adminUser);
        if(i <= 0){
            return ResultUtils.error("修改失败");
        }
        return ResultUtils.success();
    }

    @PostMapping("delete")
    @ApiOperation(value = "移除用户")
    @ApiModelProperty(value="用户id，多个使用英文逗号分隔",required = true)
    public ResultVO delete(Integer[] userIds){
        adminUserService.batchDelete(userIds);
        return ResultUtils.success();
    }

    @GetMapping("list")
    @ApiOperation(value = "查询用户列表")
    @ApiImplicitParams({ @ApiImplicitParam(name = "userName", value = "用户名" ),
            @ApiImplicitParam(name = "nickName", value = "昵称" ) })
    public PageResultVO<List<AdminUser>> list(PageDTO dto,String userName,String nickName) {
        Example example = new Example(AdminUser.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(userName)) {
            criteria.andLike("userName", "%" + userName + "%");
        }
        if (StringUtils.isNotBlank(nickName)) {
            criteria.andLike("nickName", "%" + nickName + "%");
        }
        PageHelper.startPage(dto.getPageNo(), dto.getPageSize());
        List<AdminUser> list = adminUserService.selectByExample(example);
        PageInfo<AdminUser> pageInfo = new PageInfo<>(list);
        return ResultUtils.page(pageInfo);
    }


    @PostMapping("login")
    @ApiOperation(value = "登录")
    @ApiImplicitParams({ @ApiImplicitParam(name = "userName", value = "用户名" ),
            @ApiImplicitParam(name = "passWord", value = "密码" ) })
    public ResultVO login(HttpServletRequest request,String userName, String passWord) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
        AdminUser example = new AdminUser();
        example.setUserName(userName);
        example.setPassWord(passWord);
        List<AdminUser> list = adminUserService.select(example);
        if(CollectionUtils.isEmpty(list)){
            return ResultUtils.error("用户名或密码错误");
        }
        String key = userName + "," + passWord + RandomUtils.nextInt(0,9999);
        String token = PasswordUtil.encode3Des(PasswordUtil.KEY, key);
        redisUtil.set(key,JSON.toJSONString(list.get(0)),60*60*24);
        return ResultUtils.success(token);
    }
}
